<template>
	<view class="app-container">
		<u-cell-group :border="false">
			<u-cell title="头像" border isLink @click="handleUpload">
				<view slot="value" class="u-slot-value">
					<u-avatar :src="info.avatar" shape="square" size="48"></u-avatar>
				</view>
			</u-cell>
			<u-cell title="昵称" border isLink :value="info.nickName" url="../personal/nickName"></u-cell>
			<u-cell title="性别" border isLink :value="info.sex?'女':'男'" url="../personal/gender"></u-cell>
			<u-cell title="账号" border isLink :value="info.phone"></u-cell>
			<u-cell title="修改密码" border isLink url="../personal/changePwd"></u-cell>
		</u-cell-group>
	</view>
</template>

<script>
	import {updateUserInfo} from "@/api/user.js"
	export default {
		data() {
			return {
				info: {}
			}
		},
		onShow() {
			this.getInfo()
		},
		methods: {
			handleUpload() {
				// console.log("上传头像");
				let that = this;
				uni.chooseImage({
					count: 1, // 最多可以选择的图片张数，默认9
					sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
					sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
					success: (res) => {
						that.imgUpload(res.tempFilePaths);
					}
				})
			},
			getInfo() {
				this.$store.dispatch('user/getInfo').then(res => {
					let {
						avatar,
						nickName,
						phone,
						sex
					} = res;
					this.info = {
						avatar,
						nickName,
						phone,
						sex
					};
					this.info.phone = this.formatPhone(this.info.phone)
				});
			},
			formatPhone(phone) {
				phone = phone.toString().replace(/^(.{3}).+(.{2})$/, "$1******$2");
				return phone
			},
			imgUpload(tempFilePaths) {
				let that = this;
				uni.showLoading({
					title: '正在上传…'
				});
				uni.uploadFile({
					url: this.$store.state.user.upload + '/demo/app/oss/upload', //需传后台图片上传接口
					filePath: tempFilePaths[0],
					name: 'file',
					header: {
						'X-APP-Token': uni.getStorageSync("token")
					},
					success: function(res) {
						// uni.showLoading({
						// 	title: '正在上传…'
						// });
						let { data } = JSON.parse(res.data)
						console.log(data);
						updateUserInfo({avatar:data.ossId}).then(res => {
							uni.hideLoading()
							uni.showToast({
								title: '上传成功',
								icon: "none",
								duration: 2000
							});
							that.getInfo();
						})
					},
					fail: function(error) {
						console.log('上传失败！');
						uni.hideLoading()
						uni.showToast({
							title: '上传失败！',
							icon: "none",
							duration: 2000
						})
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	.app-container {
		padding: 0 10px;
	}
</style>
